package com.hxkcloud.nurse.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hxkcloud.nurse.ActivityManager;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.alarm.Alarms;
import com.hxkcloud.nurse.beans.CheckNewMsgBean;
import com.hxkcloud.nurse.beans.LoginInfo;
import com.hxkcloud.nurse.dborm.LoginInfoDao;
import com.hxkcloud.nurse.receiver.JpushReceiver;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.BadgeUtil;
import com.hxkcloud.nurse.utils.EaseUiUtil;
import com.hxkcloud.nurse.utils.SharedPreferenceUtil;
import com.hxkcloud.nurse.utils.WebUtils;
import com.hxkcloud.nurse.views.LoadingDialog;
import com.hxkcloud.nurse.views.MyToast;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by william_sun on 2016-07-06.
 * Description:FragmentActivity基类
 */
public abstract class BaseFragmentActivity extends FragmentActivity {

    protected Context mContext;
    protected int screenWidth;
    protected int screenHeight;
    protected LoginInfo loginInfo;

    protected LoadingDialog loadingDialog;

    // 用于刷新UI
    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MessageCode.NETWORKCODE_CHECKNEWMSG_SUCCESS) {
                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                    List<CheckNewMsgBean> checkNewMsgBeans = (List<CheckNewMsgBean>) msg.obj;
                    for (CheckNewMsgBean check : checkNewMsgBeans) {
                        if (check.getName().equals("monitor")) {
                            YjhApplication.msg_monitor = check.getHaveNew().equals("1");
                        } else if (check.getName().equals("assessNurse")) {
                            YjhApplication.msg_assessNurse = check.getHaveNew().equals("1");
                        } else if (check.getName().equals("assessPatient")) {
                            YjhApplication.msg_assessPatient = check.getHaveNew().equals("1");
                        } else if (check.getName().equals("system")) {
                            YjhApplication.msg_system = check.getHaveNew().equals("1");
                        } else if (check.getName().equals("evalutionPatient")) {
                            YjhApplication.msg_evalution = check.getHaveNew().equals("1");
                        }
                        if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) &&
                                (YjhApplication.msg_assessPatient || YjhApplication.msg_system || YjhApplication.msg_chat || YjhApplication.msg_evalution)) {
                            YjhApplication.msg_new = true;
                            handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
                        } else if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) && (YjhApplication.msg_monitor || YjhApplication.msg_assessNurse
                                || YjhApplication.msg_system || YjhApplication.msg_chat)) {
                            YjhApplication.msg_new = true;
                            handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
                        } else if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_doctor)) && (YjhApplication.msg_monitor || YjhApplication.msg_assessNurse
                                || YjhApplication.msg_system)) {
                            YjhApplication.msg_new = true;
                            handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
                        } else {
                            YjhApplication.msg_new = false;
                            handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVENOT);
                        }
                    }
                    return;
                } else {
                    handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVENOT);
                }
            }
            if (msg.what == MessageCode.MSG_CHECKNEWMSG) {
                YiJiaHuNetWorkUtils.checkNewMsg(handler);
                return;
            }

            handler.post(new Runnable() {
                @Override
                public void run() {
                    dismisssLoading();
                }
            });

            if (msg.what == MessageCode.NETWORKCODE_CONNECT_ERROR) {
                dismisssLoading();
                toastMsg("网络异常，请检测网络");
            }
            if (msg.what == MessageCode.NETWORKCODE_LOGOUT_SUCCESS || msg.what == MessageCode.NETWORKCODE_LOGOUT_FAILURE) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        Alarms.clearAlarm(mContext);
                        EMClient.getInstance().logout(true);
                    }
                }.start();
                JPushInterface.setAlias(mContext, "", null);
                SharedPreferenceUtil.setIsrunning(mContext, false);
                SharedPreferenceUtil.setLoginPassword(mContext, "");
                ActivityManager.getInstance().removeAllActivity();
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            }

            updateByHandler(msg);
        }
    };


    protected abstract void updateByHandler(Message msg);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().addActivity(this);
        mContext = this;
        getScreenSize();
        loadingDialog = new LoadingDialog(this);
        getLoginInfo();
        setEMConnectionListener();

    }

    protected void getLoginInfo() {
        LoginInfoDao userDao = new LoginInfoDao(mContext);
        loginInfo = null;
        loginInfo = userDao.getUser();
    }

    private void setEMConnectionListener() {
        EMClient.getInstance().addConnectionListener(new EMConnectionListener() {
            @Override
            public void onConnected() {

            }

            @Override
            public void onDisconnected(int error) {
                if (error == EMError.USER_REMOVED) {
                    // 显示帐号已经被移除
                } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    // 显示帐号在其他设备登录
//                    toastMsg(R.string.userloginotherdevice);
                    loading();
                    YiJiaHuNetWorkUtils.logout(handler);
                } else {
                    if (WebUtils.isConnected()) {
                        //连接不到聊天服务器
                    } else {
                        //当前网络不可用，请检查网络设置
                    }
                }
            }
        });
    }

    protected void getScreenSize() {
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

        if (!this.toString().contains("ChatFragmentActivity")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (YjhApplication.StatusBarHeight > 0) {
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                } else {
                    int height = SharedPreferenceUtil.getStatusBarHeight(this);
                    if (height > 0) {
                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    }
                }
            }
        }
    }

    protected void setTitlePadding(LinearLayout l) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (YjhApplication.StatusBarHeight > 0) {
                l.setPadding(0, YjhApplication.StatusBarHeight, 0, 0);
            } else {
                int height = SharedPreferenceUtil.getStatusBarHeight(this);
                if (height > 0) {
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                }
            }
        }
    }

    private Timer mTimer;
    private myTimerTask mTimerTask;
    private EMMessageListener msgListener;

    //获取看有没有新消息
    protected void getNewMsg() {

        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                YjhApplication.msg_chat = true;
                YjhApplication.msg_new = true;
                handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
                checkNurseNewMsg();
                //EMClient.getInstance().chatManager().
                EaseUiUtil.getInstance().sendNewMsg(messages);
               // System.out.println("FragmentActivityonMessageReceived " + messages.size() + messages.get(0).getFrom());
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    protected class myTimerTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("checkNewMsg");
            Message msg = handler.obtainMessage(MessageCode.MSG_CHECKNEWMSG);
            msg.sendToTarget();
        }
    }

    /**
     * 加载
     */
    public void loading() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.setLoadingText("");
            loadingDialog.show();
        }
    }

    /**
     * 取消加载
     */
    public void dismisssLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 提示信息
     *
     * @param msg
     */
    public void toastMsg(String msg) {
        MyToast.geToast().setMsg(msg);
    }

    /**
     * 提示信息
     *
     * @param msg
     */
    public void toastMsg(int msg) {
        MyToast.geToast().setMsg(msg);
    }

    public void cancelToast() {
        MyToast.geToast().cancel();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(mContext);
        JPushInterface.onResume(mContext);
//        ZhugeSDK.getInstance().openDebug();
//        ZhugeSDK.getInstance().init(getApplicationContext());

        if (!YjhApplication.isAppActive) {
            BadgeUtil.resetBadgeCount(mContext);
            YjhApplication.isAppActive = true;
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        if (!JpushReceiver.isAppOnAtTopTask(this)) {
            YjhApplication.isAppActive = false;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(mContext);
        JPushInterface.onPause(mContext);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mTimer != null) {
            mTimer.cancel();
        }

        if (msgListener != null) {
            EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        }

        ActivityManager.getInstance().removeActivity(this);
    }

    protected void checkNurseNewMsg(){

    }
}
